﻿using NPOI.SS.Formula.Functions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunShop_WebAPI.Model;

namespace YunShop_WebAPI.BLL
{
    /// <summary>
    /// 购物车业务类
    /// </summary>
    public class ShopCartBill
    {
        /// <summary>
        /// 添加购物车
        /// </summary>
        /// <param name="FGoodsID"></param>
        /// <param name="FQty"></param>
        /// <param name="FPrice"></param>
        /// <param name="FImportsFlag"></param>
        /// <returns></returns>
        public static bool AddCart(long FGoodsID, decimal FQty, decimal FPrice, long CorpID, long FWeixinID, int FImportsFlag = 0)
        {
            StringBuilder strSql = new StringBuilder();

            List<SqlParameter> ltpara = new List<SqlParameter>
            {
                new SqlParameter("@mGoodID", FGoodsID),
                new SqlParameter("@mCorpID", CorpID),
                new SqlParameter("@OldPrice", FPrice)
            };

            FPrice = Convert.ToDecimal(DBHelper.GetDataTable(@"exec pr_wap_GetGoodPrice @mGoodID,@mCorpID,@OldPrice", ltpara.ToArray(), DBHelper.ConnMaster).Rows[0][0]);

            decimal li_Qty = GetGoodsQty(FGoodsID, FWeixinID, CorpID);
            if (li_Qty > 0)
            {
                return UpCart(FGoodsID, li_Qty + FQty, FWeixinID, CorpID);
            }
            else
            {
                strSql.Append(@"Insert Into y_Mall_Shopping(FCorpID,FWeixinID,FDate,FGoodsID,FQty,FPrice,
                  FCheckFlag,FIntegral,FImportsFlag) Values(@FCorpID,@FWeixinID,GETDATE(),@FGoodsID,@FQty,@FPrice,0,0,@FImportsFlag)");
                ltpara.Add(new SqlParameter("@FCorpID", CorpID));
                ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
                ltpara.Add(new SqlParameter("@FGoodsID", FGoodsID));
                ltpara.Add(new SqlParameter("@FQty", FQty));
                ltpara.Add(new SqlParameter("@FPrice", FPrice));
                ltpara.Add(new SqlParameter("@FImportsFlag", FImportsFlag));
                DBHelper.ExeSQL(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
                return true;
            }
        }

        /// <summary>
        /// 更新购物车
        /// </summary>
        /// <param name="FGoodsID"></param>
        /// <param name="FQty"></param>
        /// <returns></returns>
        public static bool UpCart(long FGoodsID, decimal FQty, long FWeixinID, long FCorpID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"Update y_Mall_Shopping set FQty = @FQty where FWeixinID = @FWeixinID and FGoodsID = @FGoodsID and FCorpID = @FCorpID");
            ltpara.Add(new SqlParameter("@FQty", FQty));
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FGoodsID", FGoodsID));
            ltpara.Add(new SqlParameter("@FCorpID", FCorpID));
            DBHelper.ExeSQL(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            return true;
        }

        /// <summary>
        /// 删除购物车商品
        /// </summary>
        /// <param name="FEntryID"></param>
        /// <returns></returns>
        public static bool DelCartGoods(long FEntryID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"Delete from y_Mall_Shopping where FEntryID = @FEntryID");
            ltpara.Add(new SqlParameter("@FEntryID", FEntryID));
            DBHelper.ExeSQL(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            return true;
        }

        /*  /// <summary>
          /// 删除购物车
          /// </summary>
          /// <returns></returns>
          public bool DelCart(long FWeixinID, long FCorpID)
          {
              StringBuilder strSql = new StringBuilder();
              List<SqlParameter> ltpara = new List<SqlParameter>();
              strSql.Append(@"Delete from y_Mall_Shopping where FWeixinID = @FWeixinID and FCorpID = @FCorpID");
              ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
              ltpara.Add(new SqlParameter("@FWeixinID", FCorpID));
              return DBHelper.ExecuteBySql(strSql, ltpara.ToArray());
          }*/

        /// <summary>
        /// 返回购物车商品数量
        /// </summary>
        /// <param name="FGoodsID"></param>
        /// <returns></returns>
        public static decimal GetGoodsQty(long FGoodsID, long FWeixinID, long FCorpID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select FQty from y_Mall_Shopping where FWeixinID = @FWeixinID and FGoodsID = @FGoodsID and FCorpID = @FCorpID");
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FGoodsID", FGoodsID));
            ltpara.Add(new SqlParameter("@FCorpID", FCorpID));
            ArrayList obj = DBHelper.Select(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            if (obj.Count > 0)
            {
                return Convert.ToDecimal((obj[0] as Hashtable)["FQty"].ToString());
            }
            return 0;
        }

        /// <summary>
        /// 获取购物车商品数据
        /// </summary>
        /// <returns></returns>
        public static DataTable GetShopCart(long FWeixinID, long FCorpID, int FImportFlag = -1)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select a.FEntryID,a.FCorpID,a.FGoodsID,b.FName,b.FSpec,CONVERT(float,a.FQty) as FQty,a.FIntegral,
            CONVERT(numeric(18,2),a.FPrice) as FPrice,CONVERT(numeric(18,2),b.FPosPrice) as FPosPrice,c.FBulk,
            CONVERT(numeric(18,2),a.FQty * a.FPrice) as RealMoney,b.FImportFlag,isnull(c.FWeight,0) as FWeight,
            (select top 1 REPLACE(col,'/'+CAST(1 as varchar)+'/','/'+CAST(1 as varchar)+'/Thumb/') as tcol from dbo.f_split(c.FProImage,'$')) as FThumbImage
            from y_Mall_Shopping a inner join t_Goods b on a.FGoodsID = b.FItemID left join t_GoodsDetail c on b.FItemID = c.FItemID
            where a.FWeixinID = @FWeixinID and a.FCorpID = @FCorpID");
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FCorpID", FCorpID));
            if (FImportFlag >= 0)
            {
                strSql.Append(" and b.FImportFlag = @FImportFlag");
                ltpara.Add(new SqlParameter("@FImportFlag", FImportFlag));
            }
            return DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
        }

        /*        /// <summary>
                /// 获取秒杀的商品
                /// </summary>
                /// <param name="goodsSeckillId"></param>
                /// <returns></returns>
                public DataTable GetSeckillGoods(string goodsSeckillId)
                {
                    StringBuilder strSql = new StringBuilder();
                    List<SqlParameter> ltpara = new List<SqlParameter>();
                    strSql.Append(@"select gsd.FItemID,gs.FCorpID,gsd.FGoodsID,g.FName,g.FSpec,1 as FQty,gsd.FSeckillPrce as FPrice,g.FPosPrice,gd.FBulk, gsd.FSeckillPrce as RealMoney,
                            g.FImportFlag,isnull(gd.FWeight,0) as FWeight,
                            (select top 1 REPLACE(col,'/'+CAST(1 as varchar)+'/','/'+CAST(1 as varchar)+'/Thumb/') as tcol from dbo.f_split(gd.FProImage,'$')) as FThumbImage
                            from t_GoodsSeckillDetail gsd inner join t_GoodsSeckill gs on gsd.FSeckillID = gs.FItemID
                            inner join t_Goods g on gsd.FGoodsID = g.FItemID
                            inner join t_GoodsDetail gd on g.FItemID = gd.FItemID
                            where gsd.FItemID = @FItemID");
                    ltpara.Add(new SqlParameter("@FItemID", goodsSeckillId));
                    return DBHelper.GetDataTableBySQL(strSql, ltpara.ToArray());
                }*/

        /*  /// <summary>
          /// 统计购物车总金额
          /// </summary>
          /// <returns></returns>
          public decimal SumCartRealMoney(long FWeixinID, long FCorpID)
          {
              StringBuilder strSql = new StringBuilder();
              List<SqlParameter> ltpara = new List<SqlParameter>();
              strSql.Append(@"select isnull(CONVERT(numeric(18,2),sum(FQty * FPrice)),0) as RealMoney from y_Mall_Shopping 
              where FWeixinID = @FWeixinID and FCorpID = @FCorpID");
              ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
              ltpara.Add(new SqlParameter("@FCorpID", FCorpID));
              object obj = DBHelper.GetObjectValue(strSql, ltpara.ToArray());
              if (obj != null)
              {
                  return Convert.ToDecimal(obj.ToString());
              }
              return 0;
          }
  */
        /// <summary>
        /// 统计购物车分类金额，FImportFlag (0：普通商品，1：进口商品)
        /// </summary>
        /// <param name="FWeixinID"></param>
        /// <returns></returns>
        public DataTable SumCartAccount(long FWeixinID, long FCorpID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select FImportFlag,CONVERT(numeric(18,2),SUM(FQty * FPrice)) as Total,COUNT(FGoodsID) as CountRow
            from t_Goods a inner join y_Mall_Shopping b on a.FItemID = b.FGoodsID where b.FWeixinID = @FWeixinID and b.FCorpID = @FCorpID
            group by a.FImportFlag");
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FCorpID", FCorpID));
            return DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
        }

        /// <summary>
        /// 统计购物车记录
        /// </summary>
        /// <param name="FWeixinID"></param>
        /// <returns></returns>
        public int CartCount(long FWeixinID, long FCorpID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            //strSql.Append(@"select COUNT(*) as CountRow from y_Mall_Shopping where FWeixinID = @FWeixinID and FCorpID = @FCorpID");
            strSql.Append(@"select convert(int, FQty) as CountRow from y_Mall_Shopping where FWeixinID = @FWeixinID and FCorpID = @FCorpID");
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FCorpID", FCorpID));
            //DataTable dt = DBHelper.GetDataTableBySQL(strSql, ltpara.ToArray());

            //if ((dt != null) && (dt.Rows.Count > 0))
            //{ 
            //    return dt

            //}

            //object obj = DBHelper.GetObjectValue(strSql, ltpara.ToArray());
            //if (obj != null)
            //{
            //    return Convert.ToInt32(obj.ToString());
            //}
            return 0;
        }

        /// <summary>
        /// 检查实名认证情况
        /// </summary>
        /// <param name="FWeixinID"></param>
        /// <returns></returns>
        public bool ChkRealAuth(long FWeixinID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select * from t_MemberWeixin where FWeixinID = @FWeixinID");
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            DataTable dt = DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            if (dt.Rows.Count > 0)
            {
                if (!string.IsNullOrWhiteSpace(dt.Rows[0]["FRealName"].ToString()) &&
                    !string.IsNullOrWhiteSpace(dt.Rows[0]["FIDNumber"].ToString()) &&
                    !string.IsNullOrWhiteSpace(dt.Rows[0]["FIDPic1"].ToString()) &&
                    !string.IsNullOrWhiteSpace(dt.Rows[0]["FIDPic2"].ToString()))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获取支付方式
        /// </summary>
        /// <returns></returns>
        public DataTable GetPay()
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"select * from t_Payment_Mall where FStatus = 1");
            return DBHelper.GetDataTable(strSql.ToString(), DBHelper.ConnMaster);
        }

        /*  /// <summary>
          /// 配送方式
          /// </summary>
          /// <returns></returns>
          public DataTable GetLogistType()
          {
              StringBuilder strSql = new StringBuilder();
              strSql.Append(@"select FItemID,FNumber,FName from t_Logistical where FDeleted > 0 and FCorpID = 1");
              return DBHelper.GetDataTableBySQL(strSql);
          }*/

        /// <summary>
        /// 获取运费方案
        /// </summary>
        /// <param name="CmpID">快递公司ID</param>
        /// <param name="Pid">省ID</param>
        /// <param name="Cid">市ID</param>
        /// <param name="Aid">区ID</param>
        /// <returns></returns>
        public static DataTable AccExpMoney(string CmpID, string Pid, string Cid, string Aid, long CorpID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(
                @"SELECT FItemID,FBaseQty,FFreight,FOthQty,FOthMoney,FMin,FMax,isnull(FCalculateType,0)as FCalculateType FROM t_Logistical where FCorpID = @FCorpID and FDeleted > 0");
            ltpara.Add(new SqlParameter("@FCorpID", CorpID));
            DataTable dt = DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            return dt;
        }

        /*    /// <summary>
            /// 获取会员现金券
            /// </summary>
            /// <param name="FWeixinID"></param>
            /// <returns></returns>
            public DataTable GetCoupon(long FWeixinID, long FCorpID)
            {
                StringBuilder strSql = new StringBuilder();
                List<SqlParameter> ltpara = new List<SqlParameter>();
                strSql.Append(@"select a.FItemID,a.FCorpID,a.FCouponID,c.FName,a.FNumber,a.FMemberID,a.FStartTime,
                a.FEndTime,a.FPassword,CONVERT(numeric(18,2),a.FAmount) as FAmount,a.FBillNo from y_CouponSend a inner join t_MemberWeixinCorp b
                on a.FMemberID = b.FMemberID inner join t_Coupon c on a.FCouponID = c.FItemID 
                where b.FWeixinID = @FWeixinID and a.FDeleted > 0 and a.FStatus = 0 and b.FCorpID = @FCorpID");
                ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
                ltpara.Add(new SqlParameter("@FCorpID", FCorpID));
                DataTable dt = DBHelper.GetDataTableBySQL(strSql, ltpara.ToArray());
                DataRow dr = dt.NewRow();
                dr["FItemID"] = "0";
                dr["FName"] = "请选择优惠券";
                dr["FAmount"] = "0";
                dt.Rows.InsertAt(dr, 0);
                return dt;
            }*/

        /// <summary>
        /// 保存订单
        /// </summary>

        public static bool SaveOrder(y_Mall_Shopping _model, long FWeixinID, long CorpID, string goodsSeckillId, ref long KInterID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            List<object> SqlArray = new List<object>();
            List<object> ParaArray = new List<object>();
            long agencyCorpId = CorpID;
            decimal li_RealMoney = 0;
            //取默认仓库
            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            strSql.Append(@"select FStockID from t_Corpration where FItemID = @FCorpID");
            ltpara.Add(new SqlParameter("@FCorpID", CorpID));
            string stockId = DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster).Rows[0]["FStockID"].ToString();
            //获取购物车数据
            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            decimal realMoney = 0;
            DataTable dtItem = new DataTable();
            if (_model.type == "1" && !string.IsNullOrEmpty(goodsSeckillId))
            {
                strSql.Append(
                    @"select g.FSubItemID,gsd.FGoodsID,g.FConvert,g.FName,g.FSpec,1 as FQty,0 as FIntegral,g.FLowestDis,g.FPurPrice,gsd.FSeckillPrce as FPrice,g.FPosPrice,
                      gsd.FSeckillPrce as TotalMoney,gsd.FSeckillPrce as RealMoney,gs.FCorpID,gsd.FSeckillPrce,gsd.FQty as FSeckillQty,gsd.FItemID as FSckillDetailID
                      from t_GoodsSeckillDetail gsd inner join t_Goods g on gsd.FGoodsID = g.FItemID
                      inner join t_GoodsSeckill gs on gsd.FSeckillID = gs.FItemID
                      where gsd.FItemID = @FItemID");
                ltpara.Add(new SqlParameter("@FItemID", goodsSeckillId));
                dtItem = DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            }
            else
            {
                strSql.Append(
                    @"select b.FSubItemID,a.FGoodsID,b.FConvert,b.FName,b.FSpec,CONVERT(float,a.FQty) as FQty,a.FIntegral,
                  b.FLowestDis,CONVERT(numeric(18,2),b.FPurPrice) as FPurPrice,CONVERT(numeric(18,2),a.FPrice) as FPrice,
                  CONVERT(numeric(18,2),b.FPosPrice) as FPosPrice,CONVERT(numeric(18,2),b.FPosPrice * a.FQty) as TotalMoney,
                  CONVERT(numeric(18,2),a.FQty * a.FPrice) as RealMoney,b.FCorpID,t.FSeckillPrce,t.FQty as FSeckillQty,t.FSckillDetailID
                  from y_Mall_Shopping a inner join t_Goods b on a.FGoodsID = b.FItemID 
                  left join (select * from (select gsd.FItemID as FSckillDetailID,gsd.FGoodsID,gsd.FQty,gsd.FSeckillPrce,gs.FCorpID, gs.FDelete, gs.FStartDate, gs.FEndDate,
                      row_number() over (partition by gsd.FGoodsID order by gs.FCreateDate desc) as group_idx  
                      from t_GoodsSeckillDetail gsd inner join t_GoodsSeckill gs on gsd.FSeckillID = gs.FItemID)t
                      where group_idx = 1 and FDelete > 0 and FStartDate < GETDATE() and FEndDate > GETDATE())t
                      on a.FGoodsID = t.FGoodsID and a.FCorpID = t.FCorpID
                  where a.FWeixinID = @FWeixinID and a.FCorpID = @FCorpID and b.FImportFlag = @FImportFlag ");
                ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
                ltpara.Add(new SqlParameter("@FCorpID", CorpID));
                ltpara.Add(new SqlParameter("@FImportFlag", _model.FImportsFlag));
                dtItem = DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            }
            if (dtItem == null || dtItem.Rows.Count <= 0)
            {
                return false;
            }
            else
            {
                //                DataTable dtCop = dtItem.Copy();
                //                for (int i = dtCop.Rows.Count-1; i >=0; i--)
                //                {
                //                    //按商品
                //                    DataTable dt = GetSalesPromotion(CorpID.ToString(), dtCop.Rows[i]["FGoodsID"].ToString(), stockId, "3", dtCop.Rows[i]["RealMoney"].ToString());
                //                    if (dt != null && dt.Rows.Count > 0)
                //                    {
                //                        realMoney += Convert.ToDecimal(dtCop.Rows[i]["RealMoney"]) - Convert.ToDecimal(dt.Rows[0]["FReductionAmount"]);
                //                        dtCop.Rows.RemoveAt(i);
                //                        continue;
                //                    }
                //                    //按品牌
                //
                //                }
                if (_model.type == "1")
                {
                    li_RealMoney = Convert.ToDecimal(dtItem.Compute("sum(RealMoney)", ""));
                }
                else
                    li_RealMoney = GetTotalAmount(FWeixinID.ToString(), CorpID.ToString(),
                        _model.FImportsFlag.ToString());
            }
            //应收金额
            decimal li_TotalMoney = Convert.ToDecimal(dtItem.Compute("sum(TotalMoney)", ""));
            //实收金额
            //li_RealMoney = Convert.ToDecimal(dtItem.Compute("sum(RealMoney)", ""));

            if (_model.FImportsFlag == 1)
            {
                agencyCorpId = Convert.ToInt64(dtItem.Rows[0]["FCorpID"]);
            }


            //商城订单表
            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            // string ls_CreDate = BaseFactory.DbUtils().GetDate();
            string ls_CreDate = Convert.ToDateTime(DBHelper.GetValue("SELECT GETDATE();", DBHelper.ConnMaster)).ToString("yyyy-MM-dd HH:mm:ss");
            KInterID = GetMaxAutoID("y_Mall_Master", "KInterID");
            strSql.Append(@"INSERT INTO y_Mall_Master (KInterID,FBillNo,FDate,FWeixinID,FCorpID,FAmount,FRealAmount,FTelephone,FAddress,FConsignee,FMessage,FStateID,FShippingID,FShippingAmt,FDataType,FValidFlag,FBillFlag,FBillType,FPiece,FPayType,FOrderCorpID,FStockID,FPrvID,FCityID,FAreaID,FCouponAmt)
                  values (@KInterID,@FBillNo,@FDate,@FWeixinID,@FCorpID,@FAmount,@FRealAmount,@FTelephone,@FAddress,@FConsignee,
                  @FMessage,0,@FShippingID,@FShippingAmt,5,1,@FBillFlag,@FBillType,@FPiece,0,@FOrderCorpID,@FStockID,@FPrvID,@FCityID,@FAreaID,@FCouponAmt)");

            DateTime now = DateTime.Now;
            ltpara.Add(new SqlParameter("@KInterID", KInterID));
            ltpara.Add(new SqlParameter("@FBillNo", $"{now.Year.ToString().Substring(2)}{now.Month}{now.Day}{now.Hour}{now.Minute}{KInterID + 666}"));
            ltpara.Add(new SqlParameter("@FDate", ls_CreDate));
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FCorpID", agencyCorpId));
            ltpara.Add(new SqlParameter("@FAmount", li_TotalMoney));
            ltpara.Add(new SqlParameter("@FRealAmount", li_RealMoney));
            ltpara.Add(new SqlParameter("@FTelephone", _model.FTelephone));
            ltpara.Add(new SqlParameter("@FAddress", _model.FAddress));
            ltpara.Add(new SqlParameter("@FConsignee", _model.FConsignee));
            ltpara.Add(new SqlParameter("@FMessage", _model.FMessage));
            ltpara.Add(new SqlParameter("@FShippingID", _model.FShippingID));
            ltpara.Add(new SqlParameter("@FShippingAmt", _model.FShippingAmt));
            ltpara.Add(new SqlParameter("@FBillFlag", _model.FBillFlag));
            ltpara.Add(new SqlParameter("@FBillType", _model.FImportsFlag));
            ltpara.Add(new SqlParameter("@FPiece", dtItem.Rows.Count));
            ltpara.Add(new SqlParameter("@FOrderCorpID", CorpID));
            ltpara.Add(new SqlParameter("@FStockID", stockId));
            decimal value = Convert.ToDecimal(_model.FCouponMoney);
            ltpara.Add(new SqlParameter("@FCouponAmt", value));
            ltpara.Add(new SqlParameter("@FPrvID", _model.FPrvID));
            ltpara.Add(new SqlParameter("@FCityID", _model.FCityID));
            ltpara.Add(new SqlParameter("@FAreaID", _model.FAreaID));

            /*           
              if (_model.FCouponMoney > 0 && _model.FCouponID > 0)
              {
              }
              else
              {
                  int m_FMoney = 0;
                  ltpara.Add(new SqlParameter("@FCouponAmt", m_FMoney));
              }
             */

            SqlArray.Add(strSql);
            ParaArray.Add(ltpara.ToArray());

            // 商城订单详情表
            int li_mEntryNo = 1;
            foreach (DataRow dr in dtItem.Rows)
            {
                // 修改秒杀库存
                if (!string.IsNullOrEmpty(dr["FSckillDetailID"].ToString()))
                {
                    if (Convert.ToDecimal(dr["FSeckillQty"]) <= 0)
                    {
                        return false;
                    }
                    strSql = new StringBuilder();
                    ltpara = new List<SqlParameter>();
                    strSql.Append(@"Declare @qty decimal(18,4)
                              select @qty = FQty from t_GoodsSeckillDetail where FItemID = @FSckillDetailID
                              if(@qty > @FQty)
                               INSERT INTO y_Mall_Detail (MInterID,mEntryNo,mFGoodID,mFSubItemID,mFConvert,mFQty,mFPrice,
                                              mFActualPrice,mFDiscount,mFAmount,mFRealAmount,mFCostPrice,mFQtySend,mFLargessFlag) 
                                              values (@MInterID,@mEntryNo,@mFGoodID,@mFSubItemID,@mFConvert,@mFQty,@mFPrice,@mFActualPrice,@mFDiscount,
                                              @mFAmount,@mFRealAmount,@mFCostPrice,@mFQtySend,@mFLargessFlag)");
                    ltpara.Add(new SqlParameter("@FQty", dr["FQty"].ToString()));
                    ltpara.Add(new SqlParameter("@FSckillDetailID", dr["FSckillDetailID"].ToString()));
                    ltpara.Add(new SqlParameter("@MInterID", KInterID));
                    ltpara.Add(new SqlParameter("@mEntryNo", li_mEntryNo));
                    ltpara.Add(new SqlParameter("@mFGoodID", dr["FGoodsID"].ToString()));
                    ltpara.Add(new SqlParameter("@mFSubItemID", dr["FSubItemID"].ToString()));
                    ltpara.Add(new SqlParameter("@mFConvert", dr["FConvert"].ToString()));
                    ltpara.Add(new SqlParameter("@mFQty", dr["FQty"].ToString()));
                    ltpara.Add(new SqlParameter("@mFPrice", dr["FPosPrice"].ToString()));
                    ltpara.Add(new SqlParameter("@mFActualPrice", dr["FPrice"].ToString()));
                    ltpara.Add(new SqlParameter("@mFDiscount", dr["FLowestDis"].ToString()));
                    ltpara.Add(new SqlParameter("@mFAmount", dr["TotalMoney"].ToString()));
                    ltpara.Add(new SqlParameter("@mFRealAmount", dr["RealMoney"].ToString()));
                    ltpara.Add(new SqlParameter("@mFCostPrice", dr["FPurPrice"].ToString()));
                    ltpara.Add(new SqlParameter("@mFQtySend", dr["FQty"].ToString()));
                    ltpara.Add(new SqlParameter("@mFLargessFlag", "0"));
                    li_mEntryNo++;
                    SqlArray.Add(strSql);
                    ParaArray.Add(ltpara.ToArray());

                    strSql = new StringBuilder();
                    ltpara = new List<SqlParameter>();
                    strSql.Append(
                        @"update t_GoodsSeckillDetail set FQty = FQty - @FQty where FItemID = @FSckillDetailID and FQty >= @FQty");
                    ltpara.Add(new SqlParameter("@FQty", dr["FQty"].ToString()));
                    ltpara.Add(new SqlParameter("@FSckillDetailID", dr["FSckillDetailID"].ToString()));
                    SqlArray.Add(strSql);
                    ParaArray.Add(ltpara.ToArray());
                }
                else
                {
                    strSql = new StringBuilder();
                    ltpara = new List<SqlParameter>();
                    string mFLargessFlag = "0";
                    strSql.Append(@"INSERT INTO y_Mall_Detail (MInterID,mEntryNo,mFGoodID,mFSubItemID,mFConvert,mFQty,mFPrice,
                      mFActualPrice,mFDiscount,mFAmount,mFRealAmount,mFCostPrice,mFQtySend,mFLargessFlag) 
                      values (@MInterID,@mEntryNo,@mFGoodID,@mFSubItemID,@mFConvert,@mFQty,@mFPrice,@mFActualPrice,@mFDiscount,
                      @mFAmount,@mFRealAmount,@mFCostPrice,@mFQtySend,@mFLargessFlag)");
                    ltpara.Add(new SqlParameter("@MInterID", KInterID));
                    ltpara.Add(new SqlParameter("@mEntryNo", li_mEntryNo));
                    ltpara.Add(new SqlParameter("@mFGoodID", dr["FGoodsID"].ToString()));
                    ltpara.Add(new SqlParameter("@mFSubItemID", dr["FSubItemID"].ToString()));
                    ltpara.Add(new SqlParameter("@mFConvert", dr["FConvert"].ToString()));
                    ltpara.Add(new SqlParameter("@mFQty", dr["FQty"].ToString()));
                    ltpara.Add(new SqlParameter("@mFPrice", dr["FPosPrice"].ToString()));
                    ltpara.Add(new SqlParameter("@mFActualPrice", dr["FPrice"].ToString()));
                    ltpara.Add(new SqlParameter("@mFDiscount", dr["FLowestDis"].ToString()));
                    ltpara.Add(new SqlParameter("@mFAmount", dr["TotalMoney"].ToString()));
                    ltpara.Add(new SqlParameter("@mFRealAmount", dr["RealMoney"].ToString()));
                    ltpara.Add(new SqlParameter("@mFCostPrice", dr["FPurPrice"].ToString()));
                    ltpara.Add(new SqlParameter("@mFQtySend", dr["FQty"].ToString()));
                    ltpara.Add(new SqlParameter("@mFLargessFlag", mFLargessFlag));
                    li_mEntryNo++;
                    SqlArray.Add(strSql);
                    ParaArray.Add(ltpara.ToArray());
                }
            }

            //商城订单付款表
            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            strSql.Append(@"Insert Into y_Mall_Payment(MInterID,FPayID,FPayAmount,FCutIntegral,FPayRealAmount,FCouponMoney,
                  FCouponID) values (@MInterID,@FPayID,@FPayAmount,@m_FCutIntegral,@FPayRealAmount,@FCouponMoney,@FCouponID)");
            int m_FCutIntegral = 0;
            ltpara.Add(new SqlParameter("@MInterID", KInterID));
            ltpara.Add(new SqlParameter("@FPayID", _model.FPayID));
            ltpara.Add(new SqlParameter("@m_FCutIntegral", m_FCutIntegral));

            decimal m_FPayRealAmount;
            if (_model.FCouponMoney > 0 && _model.FCouponID > 0)
            {
                m_FPayRealAmount = (li_RealMoney - _model.FCouponMoney + _model.FShippingAmt);
                ltpara.Add(new SqlParameter("@FPayAmount", (li_TotalMoney - _model.FCouponMoney) + _model.FShippingAmt));//(付款金额-优惠券)+快递费
                ltpara.Add(new SqlParameter("@FPayRealAmount", (m_FPayRealAmount > 0 ? m_FPayRealAmount : 0)));//(实收金额-优惠券)+快递费
                ltpara.Add(new SqlParameter("@FCouponMoney", _model.FCouponMoney));
                ltpara.Add(new SqlParameter("@FCouponID", _model.FCouponID));
            }
            else
            {
                int m_FMoney = 0;
                int m_FCouponID = 0;
                m_FPayRealAmount = li_RealMoney + _model.FShippingAmt;
                ltpara.Add(new SqlParameter("@FPayAmount", li_TotalMoney + _model.FShippingAmt));//(付款金额-优惠券)+快递费
                //ltpara.Add(new SqlParameter("@FPayRealAmount", li_RealMoney + _model.FShippingAmt));//实收金额+快递费
                ltpara.Add(new SqlParameter("@FPayRealAmount", (m_FPayRealAmount > 0 ? m_FPayRealAmount : 0)));//实收金额+快递费
                ltpara.Add(new SqlParameter("@FCouponMoney", m_FMoney));
                ltpara.Add(new SqlParameter("@FCouponID", m_FCouponID));
            }
            SqlArray.Add(strSql);
            ParaArray.Add(ltpara.ToArray());

            //更新优惠券为已用
            if (_model.FCouponMoney > 0 && _model.FCouponID > 0)
            {
                strSql = new StringBuilder();
                ltpara = new List<SqlParameter>();
                strSql.Append(@"Update y_CouponSend set FStatus = 1 where FItemID = @FItemID");
                ltpara.Add(new SqlParameter("@FItemID", _model.FCouponID));
                SqlArray.Add(strSql);
                ParaArray.Add(ltpara.ToArray());
            }

            //删除购物车已生成订单数据
            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            strSql.Append(@"delete from y_Mall_Shopping where FEntryID in (select a.FEntryID from y_Mall_Shopping a inner join t_Goods b 
                  on a.FGoodsID = b.FItemID where a.FWeixinID = @FWeixinID and b.FImportFlag = @FImportFlag)");
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FImportFlag", _model.FImportsFlag));
            SqlArray.Add(strSql);
            ParaArray.Add(ltpara.ToArray());

            bool v = DBHelper.BatchExecuteBySql(SqlArray.ToArray(), ParaArray.ToArray(), DBHelper.ConnMaster);
            if (v)
            {
                strSql = new StringBuilder();
                strSql.AppendFormat("Exec pr_wap_SetMallBillData {0}", KInterID);
                DBHelper.ExeSQL(strSql.ToString(), DBHelper.ConnMaster);
                strSql = new StringBuilder();
                ltpara = new List<SqlParameter>();
                SqlArray = new List<object>();
                ParaArray = new List<object>();
                return true;
            }
            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            SqlArray = new List<object>();
            ParaArray = new List<object>();
            return false;
        }

        /*     /// <summary>
             /// 获取订单总单数据
             /// </summary>
             /// <param name="KInterID"></param>
             /// <returns></returns>
             public DataTable Get_Mall_Master(long KInterID)
             {
                 StringBuilder strSql = new StringBuilder();
                 List<SqlParameter> ltpara = new List<SqlParameter>();
                 strSql.Append(@"select a.KInterID,a.FBillerID,a.FDate,a.FWeixinID,d.FNiName,a.FAmount,a.FRealAmount,a.FTelephone,a.FPayType,
                 a.FAddress,a.FConsignee,a.FMessage,a.FShippingAmt,b.FName as StateName,c.FName as FShippingName,a.FStateID,a.FShippingID
                 from y_Mall_Master a inner join t_BillState b on a.FStateID = b.FItemID inner join t_Logistical c
                 on a.FShippingID = c.FItemID inner join t_MemberWeixin d on a.FWeixinID = d.FWeixinID
                 where a.KInterID = @KInterID");
                 ltpara.Add(new SqlParameter("@KInterID", KInterID));
                 return DBHelper.GetDataTableBySQL(strSql, ltpara.ToArray());
             }
        */

        /// <summary>
        /// 获取订单收款数据
        /// </summary>
        /// <param name="KInterID"></param>
        /// <returns></returns>
        public static DataTable Get_Mall_Payment(long KInterID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            //*strSql.Append(@"select a.*,b.FName as PayName from y_Mall_Payment a inner join t_Payment_Mall b            on a.FPayID = b.FItemID where a.MInterID = @MInterID");*//*

            strSql.Append(@"select a.KInterID,a.FConsignee,a.FTelephone,a.FAddress,CONVERT(numeric(18,2),c.FPayRealAmount) as FPayRealAmount,
                 CONVERT(nvarchar(18),a.FDate,120) as FDate,d.FName as PayName,c.FPayID,a.FPiece,a.FPayType,a.FBillNo
                 from y_Mall_Master a inner join y_Mall_Payment c
                 on a.KInterID = c.MInterID inner join t_Payment_Mall d on c.FPayID = d.FItemID where a.KInterID = @KInterID");
            ltpara.Add(new SqlParameter("@KInterID", KInterID));
            return DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
        }

        /// <summary>
        /// 获取订单收款数据
        /// </summary>
        /// <param name="weiXinId"></param>
        /// <param name="fCorpId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="model"></param>
        /// <param name="buy"></param>
        /// <returns></returns>
        public static DataTable Get_Order_Payment(long weiXinId, long fCorpId, int pageIndex, int pageSize, T_OrderList model, string buy = "")
        {
            string msql = "";
            if (model.StateID != -1)
            {
                msql += string.Format(" and c.FPayType = {0}", model.StateID > 0 ? "1" : "0");
            }
            if (model.StateID >= 0)
            {
                msql += string.Format(" and c.FStateID = {0}", model.StateID);
            }
            if (buy == "0")
            {
                msql += string.Format(" and c.FStateID <> {0}", buy);
            }
            if (model.GoodsID > 0)
            {
                msql += string.Format(" and a.MInterID in (select MInterID from y_Mall_Detail where mFGoodID = {0})", model.GoodsID);
            }
            if (!string.IsNullOrWhiteSpace(model.BgDate) && !string.IsNullOrWhiteSpace(model.EnDate))
            {
                msql += string.Format(" and LEFT(CONVERT(varchar(16),c.FDate,120),10) between '{0}' and '{1}'",
                    model.BgDate, model.EnDate);
            }
            if (model.FBillType >= 0)
            {
                msql += string.Format(" and c.FBillType = {0}", model.FBillType);
            }

            List<SqlParameter> ht = new List<SqlParameter>() {
            new SqlParameter("@mPageSize",pageSize),
            new SqlParameter("@mPageIndex",pageIndex),
            new SqlParameter("@mWeiXinID",weiXinId),
            new SqlParameter("@mCorpID",fCorpId),
            new SqlParameter("@mConditon",msql),
            };

            return DBHelper.GetDataTable("pr_wap_GetOrderList @mPageSize ,@mPageIndex ,@mWeiXinID ,@mCorpID,@mConditon", ht.ToArray(), DBHelper.ConnMaster);
        }

        /// <summary>
        /// 获取订单细单
        /// </summary>
        /// <param name="MInterID"></param>
        /// <returns></returns>
        public static DataTable Get_Mall_Detail(long MInterID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select a.MEntryID,a.mFGoodID,a.mFSubItemID,a.mFQty,a.mFPrice,a.mFActualPrice,a.mFAmount,a.mFRealAmount,b.FName,b.FSpec,
             (select top 1 REPLACE(col,'/'+CAST(1 as varchar)+'/','/'+CAST(1 as varchar)+'/Thumb/') as tcol from dbo.f_split(c.FProImage,'$')) as FThumbImage
             from y_Mall_Detail a inner join t_goods b on a.mFGoodID = b.FItemid left join t_GoodsDetail c on b.FItemID = c.FItemID
             where a.MInterID = @MInterID");
            ltpara.Add(new SqlParameter("@MInterID", MInterID));
            return DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="KInterID"></param>
        /// <returns></returns>
        public static bool CancelOrder(long KInterID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"Delete from y_Mall_Master where KInterID = @KInterID");
            ltpara.Add(new SqlParameter("@KInterID", KInterID));
            try
            {
                DBHelper.ExeSQL(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;

        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="KInterID"></param>
        /// <returns></returns>
        public static bool IsCanCancelOrder(long KInterID)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append(@"select FCheckFlag from y_Mall_Master where KinterID = @KInterID");
            ltpara.Add(new SqlParameter("@KInterID", KInterID));
            DataTable dt = DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            if (dt != null && dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["FCheckFlag"].ToString() == "True")
                    return true;
                else
                    return false;
            }
            return false;
        }

        /*  /// <summary>
          /// 发货
          /// </summary>
          /// <param name="corpId"></param>
          /// <param name="weiXinId"></param>
          /// <param name="paymentId"></param>
          /// <param name="courierNumber"></param>
          /// <returns></returns>
          public bool Delivery(long corpId, long weiXinId, long paymentId, string courierNumber)
          {
              List<object> sqlArray = new List<object>();
              List<object> paraArray = new List<object>();
              StringBuilder strSql = new StringBuilder();
              List<SqlParameter> ltParams = new List<SqlParameter>();

              //取id
              strSql.Append(@"declare @MaxID int
                              exec pr_bi_GetMaxAutoID 't_Delivery','FItemID',1,@MaxID output
                              Select @MaxID as FItemID");
              long interId = Convert.ToInt64(DBHelper.GetDataTableBySQL(strSql).Rows[0][0].ToString());

              //获取该订单的商品的商品id
              strSql = new StringBuilder();
              strSql.Append(@"select mFGoodID, mFQty from y_Mall_Detail where MInterID = @MInterID");
              ltParams.Add(new SqlParameter("@MInterID", paymentId));
              DataTable dt = DBHelper.GetDataTableBySQL(strSql, ltParams.ToArray());

              strSql = new StringBuilder();
              strSql.Append(@"select FShippingID from y_Mall_Master where KInterID = @KInterID");
              ltParams.Add(new SqlParameter("@KInterID", paymentId));
              long logisticalId = Convert.ToInt64(DBHelper.GetDataTableBySQL(strSql, ltParams.ToArray()).Rows[0][0].ToString());

              strSql = new StringBuilder();
              ltParams = new List<SqlParameter>();
              strSql.Append(@"INSERT INTO t_Delivery
                                         (FItemID, FCorpID, FWeiXinID, FPaymentID, FLogisticalID, FCourierNumber)
                              VALUES     (@FItemID,@FCorpID,@FWeiXinID,@FPaymentID,@FLogisticalID,@FCourierNumber)");
              ltParams.Add(new SqlParameter("FItemID", interId));
              ltParams.Add(new SqlParameter("FCorpID", corpId));
              ltParams.Add(new SqlParameter("FWeiXinID", weiXinId));
              ltParams.Add(new SqlParameter("FPaymentID", paymentId));
              ltParams.Add(new SqlParameter("FLogisticalID", logisticalId));
              ltParams.Add(new SqlParameter("FCourierNumber", courierNumber));
              sqlArray.Add(strSql);
              paraArray.Add(ltParams.ToArray());

              strSql = new StringBuilder();
              ltParams = new List<SqlParameter>();
              strSql.Append(@"update y_Mall_Master set FStateID = 2, FExpressNumber = @FExpressNumber where KInterID = @KInterID");
              ltParams.Add(new SqlParameter("@FExpressNumber", interId));
              ltParams.Add(new SqlParameter("@KInterID", paymentId));
              sqlArray.Add(strSql);
              paraArray.Add(ltParams.ToArray());

              if (dt != null && dt.Rows.Count > 0)
              {
                  foreach (DataRow dataRow in dt.Rows)
                  {
                      strSql = new StringBuilder();
                      ltParams = new List<SqlParameter>();
                      strSql.Append(@"update t1 set FQty = (select FQty from t_StockTotal b where b.FItemID = t1.FItemID) - @FQty from t_StockTotal t1 where FGoodID = @FGoodID");
                      ltParams.Add(new SqlParameter("@FQty", dataRow["mFQty"]));
                      ltParams.Add(new SqlParameter("@FGoodID", dataRow["mFGoodID"]));
                      sqlArray.Add(strSql);
                      paraArray.Add(ltParams.ToArray());
                  }
              }

              return DBHelper.BatchExecuteBySql(sqlArray.ToArray(), paraArray.ToArray());
          }*/

        /*     /// <summary>
             /// 获取库存
             /// </summary>
             /// <param name="weixinId"></param>
             /// <param name="corpId"></param>
             /// <returns></returns>
             public DataTable GetRepertory(long weixinId, long corpId)
             {
                 StringBuilder strSql = new StringBuilder();
                 List<SqlParameter> ltParams = new List<SqlParameter>();
                 strSql.Append(@"select * from(
                         SELECT a.FItemID,a.FName, isnull(sum(c.FQty),0)as FQty
                                     FROM         t_Goods AS a INNER JOIN
                                                           y_Mall_Shopping AS b ON a.FItemID = b.FGoodsID LEFT OUTER JOIN
                                                           t_StockTotal AS c ON a.FItemID = c.FGoodID 
                                     WHERE     (b.FWeixinID = @FWeixinID) AND (b.FCorpID = @FCorpID) 
                                     group by a.FItemID,a.FName)t
                                 left join (select gsd.FGoodsID,gsd.FQty as FSeckillQty,gsd.FSeckillPrce,gs.FCorpID, gs.FDelete, gs.FStartDate, gs.FEndDate,
                             row_number() over (partition by gsd.FGoodsID order by gs.FCreateDate desc) as group_idx  
                             from t_GoodsSeckillDetail gsd inner join t_GoodsSeckill gs on gsd.FSeckillID = gs.FItemID
                                 )t2 on t.FItemID = t2.FGoodsID
                                 where t2.group_idx = 1 and t2.FCorpID = @FCorpID and t2.FDelete > 0 and t2.FStartDate < GETDATE() and t2.FEndDate > GETDATE()");
                 ltParams.Add(new SqlParameter("@FWeixinID", weixinId));
                 ltParams.Add(new SqlParameter("@FCorpID", corpId));
                 return DBHelper.GetDataTableBySQL(strSql, ltParams.ToArray());
             }*/

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="paymentId"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public static bool UpdateOrderState(string paymentId, string state)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltParams = new List<SqlParameter>();
            strSql.Append(@"select mp.FPayID 
                           from y_Mall_Master mm inner join y_Mall_Payment mp on mm.KInterID=mp.MInterID
                           where mm.KInterID = @KInterID");
            ltParams.Add(new SqlParameter("@KInterID", paymentId));
            DataTable dt = DBHelper.GetDataTable(strSql.ToString(), ltParams.ToArray(), DBHelper.ConnMaster);
            if (dt != null && dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["FPayID"].ToString() != "6")
                {
                    state = "10";
                }
            }
            strSql = new StringBuilder();
            ltParams = new List<SqlParameter>();
            strSql.Append(@"update y_Mall_Master set FStateID = @FStateID where KInterID = @KInterID");
            ltParams.Add(new SqlParameter("@FStateID", state));
            ltParams.Add(new SqlParameter("@KInterID", paymentId));
            DBHelper.ExeSQL(strSql.ToString(), ltParams.ToArray(), DBHelper.ConnMaster);
            return true;
        }
        /*
                /// <summary>
                /// 修改订单支付状态
                /// </summary>
                /// <param name="paymentId"></param>
                /// <param name="type"></param>
                /// <param name="state"></param>
                /// <returns></returns>
                public bool UpdateOrderPayType(string paymentId, string type, string state)
                {
                    StringBuilder strSql = new StringBuilder();
                    List<SqlParameter> ltParams = new List<SqlParameter>();
                    strSql.Append(@"update y_Mall_Master set FPayType = @FPayType, FStateID = @FStateID where KInterID = @KInterID");
                    ltParams.Add(new SqlParameter("@FPayType", type));
                    ltParams.Add(new SqlParameter("@FStateID", state));
                    ltParams.Add(new SqlParameter("@KInterID", paymentId));
                    return DBHelper.ExecuteBySql(strSql, ltParams.ToArray());
                }*/

        /*     /// <summary>
             /// 满送
             /// </summary>
             /// <param name="corpId"></param>
             /// <param name="orderId"></param>
             /// <returns></returns>
             public void SendFull(string corpId, string orderId)
             {
                 try
                 {
                     StringBuilder strSql = new StringBuilder();
                     List<SqlParameter> ltParams = new List<SqlParameter>();
                     strSql.Append(@"select mm.FStockID,mwc.FMemberID,mm.FRealAmount
                               from y_Mall_Master mm inner join t_MemberWeixin mw on mm.FWeixinID = mw.FWeixinID
                               inner join t_MemberWeixinCorp mwc on mwc.FWeixinID = mw.FWeixinID and mm.FCorpID = mwc.FCorpID
                               where KInterID = @KInterID");
                     ltParams.Add(new SqlParameter("@KInterID", orderId));
                     DataTable dt = DBHelper.GetDataTableBySQL(strSql, ltParams.ToArray());
                     strSql = new StringBuilder();
                     ltParams = new List<SqlParameter>();
                     strSql.Append(@"select cs.FItemID,wpd.FCouponID,wpd.FFullAmount,wp.FNumber,wp.FName
                               from t_WxPromotion wp inner join t_WxPromotionDetail wpd on wpd.FPromotionID = wp.FItemID
                               left join t_WxPromotionStock wps on wps.FPromotionID = wp.FItemID
                               left join y_CouponSend cs on wpd.FCouponID = cs.FCouponID
                               where cs.FStartTime < GETDATE() and cs.FEndTime > GETDATE() and cs.FStatus = 0 and wp.FCorpID = @FCorpID and wp.FTypeID = 2 and wp.FIsEnabled = 1
                               and wpd.FFullAmount >= @FFullAmount and wps.FStockID = @FStockID order by wp.FCreateDate desc, wpd.FFullAmount desc");
                     ltParams.Add(new SqlParameter("@FCorpID", corpId));
                     ltParams.Add(new SqlParameter("@FStockID", dt.Rows[0]["FStockID"]));
                     ltParams.Add(new SqlParameter("@FFullAmount", dt.Rows[0]["FRealAmount"]));

                     DataTable dt2 = DBHelper.GetDataTableBySQL(strSql, ltParams.ToArray());
                     if (dt2 != null && dt2.Rows.Count > 0)
                     {
                         strSql = new StringBuilder();
                         ltParams = new List<SqlParameter>();
                         strSql.Append(@"update y_CouponSend set FMemberID = @FMemberID where FItemID = @FItemID");
                         ltParams.Add(new SqlParameter("@FMemberID", dt.Rows[0]["FMemberID"]));
                         ltParams.Add(new SqlParameter("@FItemID", dt2.Rows[0]["FItemID"]));
                         DBHelper.ExecuteBySql(strSql, ltParams.ToArray());
                     }
                     else
                     {
                         strSql = new StringBuilder();
                         ltParams = new List<SqlParameter>();
                         strSql.Append(@"select cs.FItemID,wpd.FCouponID,wpd.FFullAmount,wp.FNumber,wp.FName
                               from t_WxPromotion wp inner join t_WxPromotionDetail wpd on wpd.FPromotionID = wp.FItemID
                               left join t_WxPromotionStock wps on wps.FPromotionID = wp.FItemID
                               left join y_CouponSend cs on wpd.FCouponID = cs.FCouponID
                               where cs.FStartTime < GETDATE() and cs.FEndTime > GETDATE() and wp.FCorpID = @FCorpID and wp.FTypeID = 2 and wp.FIsEnabled = 1
                               and wpd.FFullAmount >= @FFullAmount order by wp.FCreateDate desc, wpd.FFullAmount desc");
                         ltParams.Add(new SqlParameter("@FCorpID", corpId));
                         ltParams.Add(new SqlParameter("@FFullAmount", dt.Rows[0]["FRealAmount"]));
                         DataTable dt3 = DBHelper.GetDataTableBySQL(strSql, ltParams.ToArray());
                         if (dt3 != null && dt3.Rows.Count > 0)
                         {
                             strSql = new StringBuilder();
                             ltParams = new List<SqlParameter>();
                             strSql.Append(@"update y_CouponSend set FMemberID = @FMemberID where FItemID = @FItemID");
                             ltParams.Add(new SqlParameter("@FMemberID", dt.Rows[0]["FMemberID"]));
                             ltParams.Add(new SqlParameter("@FItemID", dt3.Rows[0]["FItemID"]));
                             DBHelper.ExecuteBySql(strSql, ltParams.ToArray());
                         }
                     }
                 }
                 catch (Exception e)
                 {
                     //Log.Error("<1101>SendFull==Errpr:", e.Message);
                 }
             }*/

        /*  /// <summary>
          /// 计算返利
          /// </summary>
          /// <param name="corpId"></param>
          /// <param name="orderId"></param>
          /// <returns></returns>
          public bool MemberRebate(string corpId, string orderId)
          {
              StringBuilder strSql = new StringBuilder();
              List<SqlParameter> ltpara = new List<SqlParameter>();
              List<object> SqlArray = new List<object>();
              List<object> ParaArray = new List<object>();
              strSql.Append(@"select md.MInterID,md.MEntryID,md.mFGoodID,md.mFQty,g.FPosPrice,mw.FParentID,
                      case when gd.FRebate3Type=1 then g.FRebate3 * mm.FRealAmount else g.FRebate3 end as FRebate3
                      from y_Mall_Master mm inner join y_Mall_Detail md on mm.KInterID = md.MInterID
                      inner join t_Goods g on md.mFGoodID = g.FItemID 
                      inner join t_GoodsDetail gd on g.FItemID = gd.FItemID
                      inner join t_MemberWeixin mw on mm.FWeixinID = mw.FWeixinID
                      where mm.KInterID = @KInterID");
              ltpara.Add(new SqlParameter("@KInterID", orderId));
              DataTable dt = DBHelper.GetDataTableBySQL(strSql, ltpara.ToArray());
              //统计本单总返利
              decimal totalRebate = Convert.ToDecimal(dt.Compute("sum(FRebate3)", ""));
              strSql = new StringBuilder();
              ltpara = new List<SqlParameter>();
              strSql.Append(@"select * from t_MemberRebate where FWeiXinID = @FWeiXinID");
              ltpara.Add(new SqlParameter("@FWeiXinID", dt.Rows[0]["FParentID"]));
              DataTable dt2 = DBHelper.GetDataTableBySQL(strSql, ltpara.ToArray());
              string rebateId = "";
              if (dt2 != null && dt2.Rows.Count > 0)
              {
                  rebateId = dt2.Rows[0]["FItemID"].ToString();
                  strSql = new StringBuilder();
                  ltpara = new List<SqlParameter>();
                  strSql.Append(@"update t_MemberRebate set FAmount = FAmount + @TotalRebate where FWeiXinID = @FWeiXinID");
                  ltpara.Add(new SqlParameter("@TotalRebate", totalRebate));
                  ltpara.Add(new SqlParameter("@FWeiXinID", dt.Rows[0]["FParentID"]));
                  SqlArray.Add(strSql);
                  ParaArray.Add(ltpara.ToArray());
              }
              else
              {
                  strSql = new StringBuilder();
                  ltpara = new List<SqlParameter>();
                  rebateId = BaseFactory.DbUtils().GetMaxAutoID("t_MemberRebate", "FItemID", 1).ToString();
                  strSql.Append(@"insert into t_MemberRebate(FItemID,FWeiXinID,FAmount,FCorpID)values(@FItemID,@FWeiXinID,@FAmount,@FCorpID)");
                  ltpara.Add(new SqlParameter("@FItemID", rebateId));
                  ltpara.Add(new SqlParameter("@FWeiXinID", dt.Rows[0]["FParentID"]));
                  ltpara.Add(new SqlParameter("@FAmount", totalRebate));
                  ltpara.Add(new SqlParameter("@FCorpID", corpId));
                  SqlArray.Add(strSql);
                  ParaArray.Add(ltpara.ToArray());
              }

              strSql = new StringBuilder();
              strSql.Append(@"insert into t_MemberRebateDetail(FItemID,FRebateID,MEntryID,FGoodsID,FWeiXinID,FCarentDate,FQty,FPosPrice,FRebateAmount,FDataType)
                      values(@FItemID,@FRebateID,@MEntryID,@FGoodsID,@FWeiXinID,GETDATE(),@FQty,@FPosPrice,@FRebateAmount,@FDataType)");
              foreach (DataRow dataRow in dt.Rows)
              {
                  string id = BaseFactory.DbUtils().GetMaxAutoID("t_MemberRebateDetail", "FItemID", 1).ToString();
                  ltpara = new List<SqlParameter>();
                  ltpara.Add(new SqlParameter("@FItemID", id));
                  ltpara.Add(new SqlParameter("@FRebateID", rebateId));
                  ltpara.Add(new SqlParameter("@MEntryID", dataRow["MEntryID"]));
                  ltpara.Add(new SqlParameter("@FGoodsID", dataRow["mFGoodID"]));
                  ltpara.Add(new SqlParameter("@FWeiXinID", dataRow["FParentID"]));
                  ltpara.Add(new SqlParameter("@FQty", dataRow["mFQty"]));
                  ltpara.Add(new SqlParameter("@FPosPrice", dataRow["FPosPrice"]));
                  ltpara.Add(new SqlParameter("@FRebateAmount", dataRow["FRebate3"]));
                  ltpara.Add(new SqlParameter("@FDataType", "1"));
                  SqlArray.Add(strSql);
                  ParaArray.Add(ltpara.ToArray());
              }
              return DBHelper.BatchExecuteBySql(SqlArray.ToArray(), ParaArray.ToArray());
          }*/
        /*
                /// <summary>
                /// 判断该订单是否已经支付
                /// </summary>
                /// <param name="paymentId"></param>
                /// <returns></returns>
                public bool OrderIsPay(string paymentId)
                {
                    StringBuilder strSql = new StringBuilder();
                    List<SqlParameter> ltParams = new List<SqlParameter>();
                    strSql.Append(@"select FPayType, FStateID from y_Mall_Master where KInterID = @KInterID");
                    ltParams.Add(new SqlParameter("@KInterID", paymentId));
                    DataTable dt = DBHelper.GetDataTableBySQL(strSql, ltParams.ToArray());
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["FPayType"].ToString() == "1" && dt.Rows[0]["FStateID"].ToString() == "1")
                        {
                            return true;
                        }
                    }
                    return false;
                }*/

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public static DataTable GetOrderDetail(long corpId, string orderId)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltParams = new List<SqlParameter>();
            strSql.Append(@"SELECT a.FCorpID,a.KInterID,a.FConsignee,a.FBillNo,a.FRealAmount, a.FAddress, a.FTelephone,a.FCouponAmt,a.FShippingAmt, a.FMessage, a.FStateID, a.FShippingID, a.FExpressNumber, a.FPayDate,
                                 b.FName, c.FCourierNumber,bs.FName as FStateName,
                                payment.FCouponMoney
                                 FROM         y_Mall_Master AS a LEFT OUTER JOIN
                                                       t_Logistical AS b ON a.FExpressName = b.FItemID LEFT OUTER JOIN
                                                       t_Delivery AS c ON a.FExpressNumber = c.FItemID inner join 
                                                       t_BillState bs on a.FStateID = bs.FItemID
                                 LEFT OUTER JOIN   y_Mall_Payment AS payment ON a.KInterID = payment.MInterID 
                                 WHERE     a.KInterID = @KInterID");
            ltParams.Add(new SqlParameter("@KInterID", orderId));
            //            ltParams.Add(new SqlParameter("@FCorpID", corpId));
            return DBHelper.GetDataTable(strSql.ToString(), ltParams.ToArray(), DBHelper.ConnMaster);
        }

        /// <summary>
        /// 检查是否包邮
        /// </summary>
        /// <param name="corpId"></param>
        /// <returns></returns>
        public static bool IsPinkage(long corpId)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltParams = new List<SqlParameter>();
            //strSql.Append(@"SELECT FIsPinkage FROM t_Corpration where FItemID = @FItemID");
            strSql.Append(@"SELECT FIsPinkage FROM t_Logistical where FCorpID = @FItemID");
            ltParams.Add(new SqlParameter("@FItemID", corpId));
            DataTable dt = DBHelper.GetDataTable(strSql.ToString(), ltParams.ToArray(), DBHelper.ConnMaster);
            if (dt != null && dt.Rows.Count > 0)
            {
                //if (dt.Rows[0]["FIsPinkage"].ToString() == "1")
                return true;
                //else
                //    return false;
            }
            return false;
        }
        /*
                /// <summary>
                /// 获取促销方案
                /// </summary>
                /// <param name="corpId"></param>
                /// <param name="goodsId"></param>
                /// <param name="stockId"></param>
                /// <param name="goodsScope">范围:0,全部;2,品牌;3,商品</param>
                /// <param name="fullAmount"></param>
                /// <returns></returns>
                public DataTable GetSalesPromotion(string corpId, string goodsId, string stockId, string goodsScope, string fullAmount)
                {
                    StringBuilder strSql = new StringBuilder();
                    List<SqlParameter> ltParams = new List<SqlParameter>();
                    strSql.Append(@"set datefirst 1
                          select wpd.FFullAmount,wpd.FReductionAmount,wp.FName from t_WxPromotionDetail wpd inner join t_WxPromotion wp on wpd.FPromotionID = wp.FItemID
                          left join t_WxPromotionStock wps on wps.FPromotionID = wp.FItemID

                          where CHARINDEX (CAST(datepart(weekday, getdate()) as varchar), FWeekDays) > 0 and wp.FIsEnabled = 1 and wpd.FFullAmount <= @FFullAmount and wp.FTypeID = 1
                          and wp.FGoodsScope = @FGoodsScope and wpd.FGoodsID = @FGoodsID and (wps.FStockID = @FStockID or wps.FStockID is null or wps.FStockID = 0) and wp.FCorpID = @FCorpID
                          order by wp.FCreateDate desc ");
                    ltParams.Add(new SqlParameter("@FFullAmount", fullAmount));
                    ltParams.Add(new SqlParameter("@FGoodsID", goodsId));
                    ltParams.Add(new SqlParameter("@FStockID", stockId));
                    ltParams.Add(new SqlParameter("@FCorpID", corpId));
                    ltParams.Add(new SqlParameter("@FGoodsScope", goodsScope));
                    return DBHelper.GetDataTableBySQL(strSql, ltParams.ToArray());
                }*/

        /// <summary>
        /// 获取优惠后的总金额
        /// </summary>
        /// <param name="weiXinId"></param>
        /// <param name="corpId"></param>
        /// <param name="importsFlag"></param>
        /// <returns></returns>
        public static decimal GetTotalAmount(string weiXinId, string corpId, string importsFlag)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltParams = new List<SqlParameter>();
            strSql.Append(@"exec pr_wap_GetTotalAmount @FWeixinID,@FCorpID,@FImportFlag");
            ltParams.Add(new SqlParameter("@FWeixinID", weiXinId));
            ltParams.Add(new SqlParameter("@FCorpID", corpId));
            ltParams.Add(new SqlParameter("@FImportFlag", importsFlag));
            DataTable dt = DBHelper.GetDataTable(strSql.ToString(), ltParams.ToArray(), DBHelper.ConnMaster);
            return Convert.ToDecimal(dt.Rows[0][0]);
        }


        /// <summary>
        /// 载入微信支付参数
        /// </summary>
        public static void LoadWxPayPara(string corpId)
        {
            if (string.IsNullOrEmpty(corpId)) corpId = "1";
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            strSql.Append("select * from T_WxPayPara where FCorpID = @FCorpID and Len(APPID) > 15");
            ltpara.Add(new SqlParameter("@FCorpID", corpId));
            DataTable dt = DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);

            if (dt.Rows.Count == 0)
            {
                StringBuilder strSql1 = new StringBuilder();
                List<SqlParameter> ltpara1 = new List<SqlParameter>();
                strSql1.Append("select * from T_WxPayPara where FCorpID = @FCorpID");
                ltpara1.Add(new SqlParameter("@FCorpID", 1));
                dt = DBHelper.GetDataTable(strSql1.ToString(), ltpara1.ToArray(), DBHelper.ConnMaster);
            }
            /*
                        if ((dt != null) && (dt.Rows.Count > 0))
                        {
                            WxPayConfig.APPID = dt.Rows[0]["APPID"].ToString().Trim();
                            WxPayConfig.MCHID = dt.Rows[0]["MCHID"].ToString().Trim();
                            WxPayConfig.KEY = dt.Rows[0]["PAYKey"].ToString().Trim();
                            WxPayConfig.APPSECRET = dt.Rows[0]["APPSECRET"].ToString().Trim();
                            WxPayConfig.SSLCERT_PASSWORD = dt.Rows[0]["SSLCERT_PASSWORD"].ToString().Trim();
                        }*/
        }



        public static long GetMaxAutoID(string strTablename, string strFieldname)
        {
            List<SqlParameter> ltPar = new List<SqlParameter>()
            {
                new SqlParameter("@strTablename",strTablename),
                new SqlParameter("@strFieldname",strFieldname),
            };
            Hashtable hs = DBHelper.Select(@"exec  pr_bi_GetMaxAutoIDEx @strTablename,@strFieldname", ltPar.ToArray(), DBHelper.ConnMaster)[0] as Hashtable;
            Int64? v = hs?["FLastID"] as Int64?;
            return v == null ? 1 : v.Value;
        }


    }
}
